package ui;

import static org.lwjgl.opengl.GL11.GL_LINES;
import static org.lwjgl.opengl.GL11.glBegin;
import static org.lwjgl.opengl.GL11.glEnd;
import static org.lwjgl.opengl.GL11.glVertex2f;
import static org.lwjgl.opengl.GL11.glColor3f;
import color.CLRConvert;
import util.Camera;

public class ColorScale
{
	protected static final int pxWidth = UIConst.APP_WIDTH/8;
	protected static final int pxHeight = 25;
	
	protected static final float offset_x = 25.0f; 
	private static final float offset_y = UIConst.OPTIONS_PANEL_OFFSET + 10.0f;
	
	private float[][] lines;
	protected float[][] colors;
	

	protected double min; // min and max have to be positive numbers
	protected double max;
	protected double offset; // tells the
	
	
	public int getWidth() { return pxWidth; }
	public int getHeight() { return pxHeight; }
	
	public ColorScale()
	{
		min = Double.MAX_VALUE;
		max = Double.MIN_VALUE;
		offset = 0.0;
		init();
	}
	
	private void init()
	{
		lines = new float[pxWidth][2]; // [x_pos][y_pos]
		for (int i = 0; i < pxWidth; i++)
		{
			lines[i][0] = offset_x + i;
			lines[i][1] = offset_y + pxHeight;
		}
		
		colors = new float[pxWidth][3]; // [x_pos][color]
	}
	
	public void setRange(double min, double max)
	{
		if (this.min != min || this.max != max) // same range? no need to update the scale
		{
			this.min = min;
			this.max = max;
			offset = 0.0;
			
			// get the amount we need to offset inorder to make min,max be in range 0->n
			if (min < 0)
			{
				offset = min*-1;
			}
			
			double offsetMax = max + offset;
			double offsetMin = min + offset;
			
			double slice = (offsetMax - offsetMin) / (pxWidth*1.0); // figure out the size of the increment for each pixel slice of the scale
			for (int i = 0; i < pxWidth; i++)
			{
				double wave = CLRConvert.ConvertToWaveLength(offsetMin, offsetMax, slice*i);
				float[] rgb = CLRConvert.ConvertWaveLengthToRGB(wave); // OpenGL takes color from 0.0f to 1.0f hence the div 255
				colors[i][0] = rgb[0]/255.0f;
				colors[i][1] = rgb[1]/255.0f;
				colors[i][2] = rgb[2]/255.0f;
			}
		}
	}
	
	// get the range that this color scale is representing, remember to take away the offset so the range can include negatives
	public double getMin() { return min; }
	public double getMax() { return max; }

	public void render()
	{
		Camera.setOrthoON();
        glBegin(GL_LINES);
		for (int i = 0; i < pxWidth; i++)
		{
			glColor3f(colors[i][0], colors[i][1], colors[i][2]);
			glVertex2f((float)lines[i][0], (float)offset_y);
			glVertex2f((float)lines[i][0], (float)lines[i][1]);
		}
        glEnd();
		Camera.setOrthoOFF();
	}
}
